let wxAppIdMap = {
  '110106': 'wxd22397bf8fa34ff1'
}
// 跳转到授权页面
function wechatAuthorize(redirectUrl, regorg) {
  if (regorg) {
    regorg = '110106'
  }
  let state = ''
  location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wxAppIdMap[regorg] + '&redirect_uri=' + encodeURIComponent(redirectUrl) + '&response_type=code&scope=snsapi_base&state=' + state + '#wechat_redirect'
}

/**
 * 判断当前是否是微信浏览器
 * @returns {boolean}
 */
function isWechat() {
  let ua = window.navigator.userAgent.toLowerCase()
  if (ua.indexOf('micromessenger') > -1) {
    return true
  } else {
    return false
  }
}

export default {

  wechatLogin(redirectFunction, regorg) {
    let openId = localStorage.getItem('openId_' + regorg)
    // openId为空，调用微信授权登录
    if (openId == null || openId === 'undefined' || openId === '') {
      localStorage.removeItem('openId_' + regorg)
      // 判断是否是微信端
      if (isWechat()) {
        // 在微信端自动登录
        let code = this.GetQueryString('code')
        if (code == null) {
          // 跳转到授权页面
          wechatAuthorize(location.href, regorg)
        } else {
          // 跳转授权页面成功，根据授权参数获取用户信息
          redirectFunction()
        }
      }
    } else {
      redirectFunction()
    }
  },
  GetQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) {
      return unescape(r[2])
    }
    return null
  }
}
